package com.itheima.reggie.filters;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import com.itheima.reggie.constants.Constant;
import com.itheima.reggie.utils.BaseContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: Jetwang
 * @date: 2022/4/10 19:46
 * @description: LoginCheckFilter 登录过滤器
 * @version: 1.0
 */
@Slf4j
public class LoginCheckFilter implements Filter {
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        log.info("拦截到请求: {}", requestURI);
        // 定义不需要拦截的路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**"
        };

        // 判断本次请求是否需要处理
        boolean check = check(urls, requestURI);
        if (check) {
            // 放行
            log.info("本次请求{}不需要处理", requestURI);
            filterChain.doFilter(request, response);
            return;
        };
        // 判断用户是否已经完成登录
        if (request.getSession().getAttribute(Constant.LOGIN_SESSION) != null) {
            // 放行
            log.info("用户已经登录,用户id：{}", request.getSession().getAttribute(Constant.LOGIN_SESSION));
            // 将当前用户的id存放到ThreadLocal中
            Long id = (Long) request.getSession().getAttribute(Constant.LOGIN_SESSION);
            BaseContextUtil.setCurrentId(id);
            filterChain.doFilter(request, response);
            return;
        }
        // 输出流返回
        log.info("用户未登录");
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     * 进行路径匹配
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }

}
